package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.pojos.UserLikeBehavior;
import com.heima.article.pojos.UserLoveBehavior;
import com.heima.article.service.ApUserBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.ArticleBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.article.vo.ArticleBehaviorVo;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserBehaviorServiceImpl implements ApUserBehaviorService {
    @Autowired
    private ApCollectionMapper apCollectionMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户收藏
     * @param dto
     * @return
     */
    @Override
    public ResponseResult userCollection(CollectionBehaviorDto dto) {
        //1.参数校验
        if (dto==null || dto.getEntryId()==null || dto.getOperation()==null || dto.getPublishedTime()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.获取当前用户id，查询是否存在该文章的收藏数据
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if (userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.判断用户的操作类型：0新增数据，1删除
        if (dto.getOperation()==0){
            ApCollection apCollection = new ApCollection();
            apCollection.setUserId(Long.valueOf(userId));
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublishedTime());
            apCollectionMapper.insert(apCollection);
            //存储到redis中
            redisTemplate.opsForHash().put(BehaviorConstants.BEHAVIOR_COLLECTION+dto.getEntryId(),
                    BehaviorConstants.BEHAVIOR_IS_COLLECTION+userId,"1");
        }
        if (dto.getOperation()==1){
            LambdaQueryWrapper<ApCollection> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApCollection::getUserId,userId)
                    .eq(ApCollection::getArticleId,dto.getEntryId())
                    .eq(ApCollection::getType,dto.getType());
            apCollectionMapper.delete(queryWrapper);
            //删除redis中的缓存数据
            redisTemplate.opsForHash().delete(BehaviorConstants.BEHAVIOR_COLLECTION+dto.getEntryId(),
                    BehaviorConstants.BEHAVIOR_IS_COLLECTION+userId);
        }

        return ResponseResult.okResult("");
    }


    /**
     * 加载用户行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.校验参数
        if (dto==null || dto.getArticleId()==null || dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.查看当前用户对文章的行为
        //2.1获取当前用户的id
        Integer userId = AppThreadLocalUtil.getUser().getId();

        ArticleBehaviorVo vo = new ArticleBehaviorVo();
        //2.2查询是否点赞，查询mongoDB
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("userId").is(userId));
        UserLikeBehavior likeBehavior = mongoTemplate.findOne(query, UserLikeBehavior.class);
        if (likeBehavior.getOperation()==0){
            vo.setIslike(true);
        }else {
            vo.setIslike(false);
        }

        //2.3查询是否不喜欢。查询mongoDB
        UserLoveBehavior loveBehavior = mongoTemplate.findOne(query, UserLoveBehavior.class);
        if (loveBehavior.getType()==0){
            vo.setIsunlike(true);
        }else {
            vo.setIsunlike(false);
        }

        //2.4查询用户是否收藏。查询redis(存在收藏，不存在为收藏)
        Object key = redisTemplate.opsForHash().get(BehaviorConstants.BEHAVIOR_COLLECTION + dto.getArticleId(),
                BehaviorConstants.BEHAVIOR_IS_COLLECTION + userId);
        if (key != null){
            vo.setIscollection(true);
        }else {
            vo.setIscollection(false);
        }

        //2.5查询用户是否关注，查询redis(存在关注)
        final Object key1 = redisTemplate.opsForHash().get(BehaviorConstants.BEHAVIOR_FOLLOW + dto.getAuthorId(),
                BehaviorConstants.BEHAVIOR_IS_FOLLOW + userId);
        if (key1 != null){
            vo.setIsfollow(true);
        }else {
            vo.setIsfollow(false);
        }

        return ResponseResult.okResult(vo);
    }

}
